package com.sd.repay.controller;

import com.sd.repay.common.CommonResult;
import com.sd.repay.pojo.ScheduleJob;
import com.sd.repay.service.JobTaskService;
import com.sd.repay.utils.SpringUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

@Controller
@RequestMapping("/taskMgr")
public class JobTaskController {

    // 日志记录器
    public final Logger log = LoggerFactory.getLogger(JobTaskController.class);

    public String repayAccessMobile = WebUtil.getSysValue("REPAY_TASK_ACCESS_MOBILE");
    public String[] mobileArray;

    public String repayAccessIp = WebUtil.getSysValue("REPAY_ACCESS_IP");
    public String[] ipArray;

    {
        if (StringUtils.isNotEmpty(repayAccessMobile)) {
            mobileArray = repayAccessMobile.split(",");
        }
        if (StringUtils.isNotEmpty(repayAccessIp)) {
            ipArray = repayAccessIp.split(",");
        }
    }

    @Autowired
    private JobTaskService taskService;


    /**
     * 定时任务列表页面
     *
     * @param request
     * @return
     */
    @RequestMapping("taskList")
    public String taskList(HttpServletRequest request) {
        boolean isAccess = false;
        try {
            //判断IP限制
            String accessIp = WebUtil.getIpAddr(request);
            log.info("定时任务页面访问IP：" + accessIp);
            if (ipArray != null && ipArray.length > 0) {
                for (String ip : ipArray) {
                    if (ip.equals(accessIp)) {
                        isAccess = true;
                    }
                }
            } else {
                isAccess = true;
            }

            if (!isAccess) {
                //判断手机号
                String mobile = request.getParameter("mobile");
                if (StringUtils.isNotEmpty(mobile)) {
                    for (String mo : mobileArray) {
                        if (mo.equals(mobile)) {
                            isAccess = true;
                        }
                    }
                }
            }

            if (isAccess) {
                log.info("获取定时任务列表");
                List<ScheduleJob> taskList = taskService.getAllTask();
                request.setAttribute("taskList", taskList);
                return "taskList";
            }

        } catch (Exception e) {
            log.error("获取定时任务列表异常：" + e.getMessage());
        }
        return "noAccess";
    }

    /**
     * 修改定时任务状态
     *
     * @param jobId
     * @param jobStatus
     * @return
     */
    @RequestMapping("changeJobStatus")
    @ResponseBody
    public CommonResult changeJobStatus(String jobId, String jobStatus) {
        try {
            taskService.updateStatus(jobId, jobStatus);
        } catch (Exception e) {
            log.error("修改定时任务状态异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    /**
     * 修改cron表达式
     *
     * @param jobId
     * @param cron
     * @return
     */
    @RequestMapping("updateCron")
    @ResponseBody
    public CommonResult updateCron(String jobId, String cron) {
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
            taskService.updateCron(jobId, cron);
        } catch (Exception e) {
            log.error("修改定时cron表达式异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    /**
     * 修改预警时间
     *
     * @param jobId
     * @param warnTime
     * @return
     */
    @RequestMapping("updateWarnTime")
    @ResponseBody
    public CommonResult updateWarnTime(String jobId, String warnTime) {
        try {
            try {
                Long warnTimeL = Long.parseLong(warnTime);
            } catch (Exception e) {
                return CommonResult.build(403, "预警时间不合法，请重新输入");
            }
            taskService.updateWarnTime(jobId, warnTime);
        } catch (Exception e) {
            log.error("修改预警时间异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    /**
     * 新增定时任务
     *
     * @param scheduleJob
     * @return
     */
    @RequestMapping("addTask")
    @ResponseBody
    public CommonResult addTask(ScheduleJob scheduleJob) {
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
        } catch (Exception e) {
            log.error("cron表达式有误，不能被解析");
            return CommonResult.build(403, "cron表达式有误，不能被解析");
        }
        Object obj = null;
        try {
            if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
                obj = SpringUtil.getBean(scheduleJob.getSpringId());
            } else {
                Class clazz = Class.forName(scheduleJob.getBeanClass());
                obj = clazz.newInstance();
            }
        } catch (Exception e) {
            log.error("新增失败，请稍候再试" + e.getMessage());
            return CommonResult.build(403, "新增失败，请稍候再试");
        }
        if (obj == null) {
            return CommonResult.build(403, "未找到目标类");
        } else {
            Class clazz = obj.getClass();
            Method method = null;
            try {
                method = clazz.getMethod(scheduleJob.getMethodName(), null);
            } catch (Exception e) {
                log.error("新增失败，请稍候再试" + e.getMessage());
                return CommonResult.build(403, "新增失败，请稍候再试");
            }
            if (method == null) {
                return CommonResult.build(403, "未找到目标方法");
            }
        }
        try {
            int count = taskService.addTask(scheduleJob);
            log.info("新增定时任务影响的行数：" + count);
        } catch (Exception e) {
            log.error("新增失败，请稍候再试" + e.getMessage());
            return CommonResult.build(403, "新增失败，请稍候再试");
        }
        return CommonResult.ok();
    }


    @RequestMapping("pauseJob")
    @ResponseBody
    public CommonResult pauseJob(String jobId) {
        try {
            ScheduleJob scheduleJob = taskService.getTaskById(jobId);
            taskService.pauseJob(scheduleJob);
        } catch (Exception e) {
            log.error("暂停定时任务" + jobId + "异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    @RequestMapping("resumeJob")
    @ResponseBody
    public CommonResult resumeJob(String jobId) {
        try {
            ScheduleJob scheduleJob = taskService.getTaskById(jobId);
            taskService.resumeJob(scheduleJob);
        } catch (Exception e) {
            log.error("恢复定时任务" + jobId + "异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    @RequestMapping("deleteJob")
    @ResponseBody
    public CommonResult deleteJob(String jobId) {
        try {
            ScheduleJob scheduleJob = taskService.getTaskById(jobId);
            taskService.deleteJob(scheduleJob);
        } catch (Exception e) {
            log.error("删除定时任务" + jobId + "异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    @RequestMapping("runAJobNow")
    @ResponseBody
    public CommonResult runAJobNow(String jobId) {
        try {
            ScheduleJob scheduleJob = taskService.getTaskById(jobId);
            taskService.runAJobNow(scheduleJob);
        } catch (Exception e) {
            log.error("立即执行定时任务" + jobId + "异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }

    @RequestMapping("stopJob")
    @ResponseBody
    public CommonResult stopJob(String jobId) {
        try {
            ScheduleJob scheduleJob = taskService.getTaskById(jobId);
            taskService.stopJob(scheduleJob);
        } catch (Exception e) {
            log.error("停止定时任务" + jobId + "异常：" + e.getMessage());
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
        return CommonResult.ok();
    }
}
